package com.crazy.cloud.common.advice;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import feign.FeignException;
import feign.Response;
import feign.Util;
import feign.codec.ErrorDecoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Configuration;

/**
 * @program: crazy-cloud
 * @description: feign异常处理
 * @author: CrazyMan
 * @create: 2018/9/29 上午11:52
 **/
//@Slf4j
//@Configuration
public class ExceptionErrorDecoder implements ErrorDecoder {

    @Override
    public Exception decode(String methodKey, Response response) {
        try {
            if (response.body() != null) {
                ExceptionInfo exceptionInfo = JSON.parseObject(Util.toString(response.body().asReader()), new TypeReference<ExceptionInfo>() {
                });
                Class clazz = Class.forName(exceptionInfo.getException());
                return (Exception) clazz.getDeclaredConstructor(String.class).newInstance(exceptionInfo.getMessage());
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return FeignException.errorStatus(methodKey, response);
    }
}
